package com.apache.attachment.service.plugins;

import java.io.File;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.attachment.entity.AttachmentRegister;
import com.apache.attachment.entity.AttachmentStore;
import com.apache.attachment.manager.AttachmentRegisterManager;
import com.apache.attachment.manager.AttachmentStoreManager;
import com.apache.attachment.mommon.AttachmentConfig;
import com.apache.cache.util.Validator;
import com.apache.tools.StrUtil;

public class DelAttaPlugin implements PluginConnector {

	private Logger logger = LoggerFactory.getLogger(DelAttaPlugin.class);

	private AttachmentRegisterManager attachmentRegisterManager;
	private AttachmentStoreManager attachmentStoreManager;

	@Override
	public Object execute(ParamsVo param) throws Exception {
		this.logger.info("---------进入插件DelAttaPlugin----");
		String key = param.getMethodKey();
		ResultEntity result = new ResultEntity();

		String objType = null;
		String objId = null;
		String id = null;

		AttachmentRegister ar = null;

		ResultMsg rmsg = null;
		String attaSort = null;

		if ("delAttaById".equals(key)) {//
			//校验附件信息id
			id = String.valueOf(param.getParams("id"));
			if (Validator.isNull(id)) {
				result.setResult("false");
				result.setMessage("接口必要参数为空！");
				return result;
			}

			//校验附件是否存在
			ParamsVo<AttachmentStore> vo = new ParamsVo<AttachmentStore>();
			vo.setInfoId(id);
			AttachmentStore as = (AttachmentStore) attachmentStoreManager.getInfoById(vo);
			if (Validator.isEmpty(as)) {
				result.setResult("false");
				result.setMessage("附件不存在或者已经删除！");
				return result;
			}

			//校验objType字段数据库数据
			objType = as.getObjType();
			if (Validator.isNull(objType)) {
				result.setResult("false");
				result.setMessage("objType为空,附件信息数据异常!");
				return result;
			}

			//校验注册信息
			ar = getRegister(objType);
			if (Validator.isEmpty(ar)) {
				result.setResult("false");
				result.setMessage("实体未注册!");
				return result;
			}

			//权限检查
			String ip = StrUtil.doNull(ar.getIpAddress());
			if (StrUtil.isNotEmptyWithTrim(ip)) {
				boolean ipflag = checkIp(String.valueOf(param.getParams("remoteAddr")), ar.getIpAddress());
				if (!ipflag) {
					result.setResult("false");
					result.setMessage("无访问权限！");
					return result;
				}
			}

			//校验注册类型
			attaSort = ar.getAttaSort();
			if (Validator.isNull(attaSort)) {
				result.setResult("false");
				result.setMessage("实体注册类型为空!");
				return result;
			}

			rmsg = this.delete(id, attaSort, String.valueOf(param.getParams("reqUploadPath")));
			if ("T".equals(rmsg.getFlag())) {
				result.setMessage("操作成功!");
				result.setResult("true");
			} else {
				result.setMessage("操作失败!");
				result.setResult("false");
			}

		} else if ("delAttaByObjId".equals(key)) {
			objType = String.valueOf(param.getParams("objType"));
			objId = String.valueOf(param.getParams("objId"));
			this.logger.info("--------objType=" + objType + ";objId=" + objId);
			System.out.println("--------objType=" + objType + ";objId=" + objId);

			if (Validator.isNull(objType) || Validator.isNull(objId)) {
				result.setResult("false");
				result.setMessage("接口必要参数为空！");
				return result;
			}

			ar = getRegister(objType);
			if (Validator.isEmpty(ar)) {
				result.setResult("false");
				result.setMessage("实体未注册!");
				return result;
			}

			attaSort = ar.getAttaSort();
			if (Validator.isNull(attaSort)) {
				result.setResult("false");
				result.setMessage("实体注册类型为空!");
				return result;
			}

			//权限检查
			String ip = StrUtil.doNull(ar.getIpAddress());
			if (StrUtil.isNotEmptyWithTrim(ip)) {
				boolean ipflag = checkIp(String.valueOf(param.getParams("remoteAddr")), ar.getIpAddress());
				if (!ipflag) {
					result.setResult("false");
					result.setMessage("无访问权限！");
					return result;
				}
			}

			ParamsVo vo = new ParamsVo();
			AttachmentStore as = new AttachmentStore();
			as.setObjId(objId);
			as.setObjType(objType);
			vo.setObj(as);
			List<AttachmentStore> asList = attachmentStoreManager.getList(vo);
			AttachmentStore store = null;
			if (!Validator.isEmpty(asList)) {
				for (int i = 0; i < asList.size(); i++) {
					store = asList.get(i);
					rmsg = this.delete(store.getSid(), attaSort, String.valueOf(param.getParams("reqUploadPath")));
					if ("F".equals(rmsg.getFlag())) {
						result.setMessage("操作失败!");
						result.setResult("false");
						return result;
					}
				}
				result.setMessage("操作成功!");
				result.setResult("true");
			} else {
				result.setMessage("无附件信息!");
				result.setResult("false");
			}
		}
		return result;
	}

	/**
	 * 删除附件及信息  
	 */
	private ResultMsg delete(String id, String attaSort, String reqUploadPath) {
		ResultMsg rmsg = new ResultMsg();
		rmsg.setFlag("T");
		rmsg.setMsg("操作成功！");

		if (Validator.isNull(id)) {
			rmsg.setFlag("F");
			rmsg.setMsg("缺少必要的参数!");
			return rmsg;
		}

		//校验附件是否存在
		ParamsVo<AttachmentStore> vo = new ParamsVo<AttachmentStore>();
		vo.setInfoId(id);
		AttachmentStore as = (AttachmentStore) attachmentStoreManager.getInfoById(vo);
		if (Validator.isEmpty(as)) {
			rmsg.setFlag("F");
			rmsg.setMsg("附件不存在或者已经删除！");
		}

		String attafileName = as.getSid() + "." + as.getAttachmentType();
		String uploadDir = getUploadDir(reqUploadPath, id, as);
		if (Validator.isNull(uploadDir)) {
			rmsg.setFlag("F");
			rmsg.setMsg("上传路径为空，请检查配置文件或者程序异常！");
			return rmsg;
		}

		String uploadDirpro = uploadDir + attafileName;

		boolean mark = attachmentStoreManager.deleteInfo(vo);
		if (!mark) {
			rmsg.setFlag("F");
			rmsg.setMsg("操作失败！");
			return rmsg;
		}

		if (Validator.isNotNull(attaSort) && "1".equals(attaSort.trim())) {
			String wrMiddleFileName = as.getSid() + ".m." + as.getAttachmentType();//中图名
			logger.info("wrMiddleFileName[{}]" + wrMiddleFileName);
			String uploadDirm = uploadDir + wrMiddleFileName;//中图上传地址
			String wrSmallFileName = as.getSid() + ".s." + as.getAttachmentType();//小图名
			logger.info("wrSmallFileName[{}]" + wrSmallFileName);
			String uploadDirs = uploadDir + wrSmallFileName;//小图上传地址

			File file = new File(uploadDirpro);
			File filem = new File(uploadDirm);
			File files = new File(uploadDirs);

			if (file.exists() && filem.exists() && files.exists()) {
				boolean ob = file.delete();
				boolean obm = filem.delete();
				boolean obs = files.delete();
				if (ob & obm && obs) {
					rmsg.setFlag("T");
					rmsg.setMsg("操作成功！");
				} else {
					rmsg.setFlag("F");
					rmsg.setMsg("操作失败！");
					return rmsg;
				}
			} else {
				rmsg.setFlag("T");
				//rmsg.setMsg("图片信息已删除，但没有找到图片！");
				rmsg.setMsg("图片不存在或者已删除！");
			}
		} else {
			File file = new File(uploadDirpro);
			if (file.exists()) {
				boolean ob = file.delete();
				if (ob) {
					rmsg.setFlag("T");
					rmsg.setMsg("操作成功！");
				} else {
					rmsg.setFlag("F");
					rmsg.setMsg("操作失败！");
					return rmsg;
				}
			} else {
				rmsg.setFlag("T");
				//rmsg.setMsg("附件信息已删除，但没有找到附件！");
				rmsg.setMsg("附件不存在或者已删除！");
			}

		}

		return rmsg;
	}

	/**
	 * 访问ip验证
	 */
	private boolean checkIp(String userIp, String defineIp) {
		String uIp = StrUtil.doNull(userIp);
		String defIp = StrUtil.doNull(defineIp);
		if (StrUtil.isEmptyWithTrim(defIp)) {
			return true;
		}
		if (defIp.indexOf(uIp) != -1) {
			return true;
		}
		return false;
	}

	/**
	 * 通过objType得到实体注册信息
	 */
	public AttachmentRegister getRegister(String objType) {
		AttachmentRegister ar = new AttachmentRegister();
		ar.setRegEname(objType);
		ParamsVo vo = new ParamsVo();
		vo.setObj(ar);
		List<AttachmentRegister> arList = attachmentRegisterManager.getList(vo);
		if (arList.size() > 0) {
			ar = arList.get(0);
		}
		return ar;
	}

	/**
	 * description:获得上传目录  
	 * @author mhguo 
	 * @update 2015-5-28
	 */
	public String getUploadDir(String reqUploadPath, String id, AttachmentStore as) {
		String uploadPath = AttachmentConfig.getProp("UPLOAD_DIRECTORY");
		String downloadUrl = AttachmentConfig.getProp("DOWNLOAD_URL");
		if (StrUtil.isEmptyWithTrim(uploadPath)) {
			if (Validator.isNotNull(reqUploadPath)) {
				uploadPath = reqUploadPath;
			} else {
				return null;
			}
		}
		//java中使用正则获得路径
		String regEx = downloadUrl;
		Pattern pat = Pattern.compile(regEx);
		Matcher mat = pat.matcher(as.getDownloadUrl());
		String filePath_ = mat.replaceAll("");
		String attaFilePath = filePath_.substring(1, filePath_.lastIndexOf("/"));
		String uploadDir = uploadPath + File.separator + attaFilePath + File.separator;
		return uploadDir;
	}

	public void setAttachmentRegisterManager(AttachmentRegisterManager attachmentRegisterManager) {
		this.attachmentRegisterManager = attachmentRegisterManager;
	}

	public void setAttachmentStoreManager(AttachmentStoreManager attachmentStoreManager) {
		this.attachmentStoreManager = attachmentStoreManager;
	}

}
